<!DOCTYPE html>
<html lang="zh">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>Document</title>
</head>
<body>
	<canvas id="canvas" width="400" height="400"></canvas>
	
	<script>
		//封装一个箭头类
		class Arrow{
			constructor() {
			  this.x = 0;
				this.y = 0;
				this.color = "#ffff00";
				this.rotation = 0;
			}
			draw(context){
				context.save();
				context.translate(this.x, this.y); //重新映射画布上的 (0,0) 位置
				context.rotate(this.rotation);  //旋转当前绘图
				context.lineWidth = 2;
				context.fillStyle = this.color;
				context.beginPath();
				context.moveTo(-50, -25);
				context.lineTo(0, -25);
				context.lineTo(0, -50);
				context.lineTo(50, 0);
				context.lineTo(0, 50);
				context.lineTo(0, 25);
				context.lineTo(-50, 25);
				context.lineTo(-50, -25);
				context.closePath();
				context.fill();
				context.stroke();
				context.restore();
			}
		}
		//封装一个显示鼠标位置的方法
		function CaptureMouse(element){
			let mouse = {x:0, y:0};
			element.addEventListener('mousemove', function(e){
				let x, y;
				if(e.pageX || e.pageY){
					x = e.pageX;
					y = e.pageY;
				}else{
					x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
					y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
				}
				
				x -= element.offsetLeft;
				y -= element.offsetTop;
				
				mouse.x = x;
				mouse.y = y;
			}, false);
			return mouse;
		}
		
		
		var canvas = document.getElementById('canvas'),
				context = canvas.getContext('2d'),
				arrow = new Arrow(),
				speed = 1,
				mouse = CaptureMouse(canvas);
		
		/* canvas.addEventListener('mousedown', function(){
			console.log('x: ' + mouse.x + ',y: ' + mouse.y);
		}, false); */
		
		(function drawFrame(){
			window.requestAnimationFrame(drawFrame, canvas);
			context.clearRect(0, 0, canvas.width, canvas.height);
			var dx = mouse.x - arrow.x,
					dy = mouse.y - arrow.y,
					angle = Math.atan2(dy, dx),
					vx = Math.cos(angle) * speed,
					vy = Math.sin(angle) * speed;
			
			arrow.rotation = angle;
			arrow.x += vx;
			arrow.y += vy;
			arrow.draw(context);
		}());
			
				
				
		
	</script>
</body>
</html>